package PingPong;

import java.net.*;
import java.io.*;

public class Server  {
	public Server() {
		try {
			ServerSocket server = new ServerSocket(Commons.PORT);
			
			System.out.println("Waiting for players...");
			left = new PlayerClient( server.accept(), "left" );
			right = new PlayerClient( server.accept(), "right" );
			
			left.setOpponent(right);
			right.setOpponent(left);
			
			System.out.println("Game commercing.");
			
			Thread tLeft = new Thread( left );
			tLeft.start();
			
			Thread tRight = new Thread( right );
			tRight.start();
			
			left.send("start");
			right.send("start");
		} catch( IOException e ) {
			
		}
	}
	
	private class PlayerClient implements Runnable {
		public PlayerClient( Socket s, String m ) {
			try {
				in = new BufferedReader(new InputStreamReader(s.getInputStream()));
				out = new PrintWriter(s.getOutputStream(), true);
				out.println(m);
				
				System.out.println("Player connected.");
			} catch( IOException e ) {
				
			}
		}
		
		public void setOpponent( PlayerClient o ) {
			opponent = o;
		}
		
		public void send( String msg ) {
			out.println( msg );
		}
	
		public void run() {
			try {
				while( true ) {
					String m = in.readLine();
					
					opponent.send(m);
				}
			} catch( IOException e ) {
				opponent.send("end");
			}
		}
		
		private BufferedReader in;
		private PrintWriter out;
		private PlayerClient opponent;
	}
	
	public static void main(String[] args) {
		new Server();
	}

	private PlayerClient left, right;
}
